﻿#if UNITY_EDITOR
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;


namespace AI.Graph.Editor {


    public abstract class ParameterDrawer<T> : PropertyDrawer where T : Parameter {

        public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
            UnityEditor.EditorGUI.BeginProperty (position, label, property);


            if (property.serializedObject.targetObject.IsTypeOf<Node> ()) {
                Node node = (Node) property.serializedObject.targetObject;

                if (node.controller == null) return;

                FieldInfo[] fields = ReflectionUtility.GetFields (node.GetType (), typeof (T));
                for (int i = 0; i < fields.Length; i++) {
                    FieldInfo field = fields[i];

                    if (field.Name == property.name) {
                        ParameterType parameterType = field.GetAttribute<ParameterType> (true);
                        if (parameterType != null) {
                            GUILayout.Space (-18);
                            OnParameterGUI (parameterType.label ?? label.text, property, parameterType.type, node);
                        }
                        else {
                            OnInfoGUI (position, label, "Needs ParameterType Attribute");
                        }
                    }
                }
            }
            else {
                OnInfoGUI (position, label, "can only be used with Nodes");
            }

            UnityEditor.EditorGUI.EndProperty ();
        }


        void OnInfoGUI (Rect position, GUIContent label, string info) {
            Rect labelRect = new Rect (position.x, position.y, UnityEditor.EditorGUIUtility.labelWidth, position.height);
            Rect infoRect = new Rect (position.x + UnityEditor.EditorGUIUtility.labelWidth, position.y, position.width - UnityEditor.EditorGUIUtility.labelWidth, position.height);
            GUI.Label (labelRect, label);
            GUI.Label (infoRect, info);
        }


        protected abstract void OnParameterGUI (string title, SerializedProperty parameterProperty, Type type, Node node);

    }


}
#endif